package com.whosly.fast.web.quickly.command;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Component
public class CheckDataSourceCommandLineRunner implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(CheckDataSourceCommandLineRunner.class);

    @Resource
    private DataSource dataSource;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(dataSource == null) {
            logger.error("dataSource is null!");
            return;
        }

        logger.info("dataSource:{}", dataSource.getClass().getName());
        Connection connection = dataSource.getConnection();
        logger.info("connection:{}", connection.toString());

        String sql = "select * from t1";
        List<T1> rs = jdbcTemplate.query(sql, TestTableRowMapper.INSTANCE);
        logger.info("query result:{}", rs);
    }

    public record T1(
            Long c1,
            String c2) {}

    static class TestTableRowMapper implements RowMapper<T1> {
        public static final TestTableRowMapper INSTANCE = new TestTableRowMapper();

        private TestTableRowMapper(){}

        @Override
        public T1 mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new T1(
                    rs.getLong("c1"),
                    rs.getString("c2")
            );
        }
    }
}
